package com.jian.mall.produce.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;

@Slf4j
public class RedisCache implements Cache {
    private final String id;

    public RedisCache(String id) {
        log.info("RedisCache id ====> " + id);
        this.id = id;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void putObject(Object key, Object value) {
        RedisTemplate<Object,Object> redisTemplate =
                (RedisTemplate<Object,Object>) ApplicationContextUtils.getBean("redisTemplate");
        log.info("RedisCache putObject ----> key:" + key.toString() + " \n---- value:" + value.toString());
        redisTemplate.opsForHash().put(id, key, value);
    }

    @Override
    public Object getObject(Object key) {
        RedisTemplate<Object,Object> redisTemplate =
                (RedisTemplate<Object,Object>) ApplicationContextUtils.getBean("redisTemplate");
        log.info("RedisCache getObject ----> key:" + key.toString());
        return redisTemplate.opsForHash().get(id, key);
    }

    @Override
    public Object removeObject(Object key) {
        RedisTemplate<Object,Object> redisTemplate =
                (RedisTemplate<Object,Object>) ApplicationContextUtils.getBean("redisTemplate");
        log.info("RedisCache removeObject ----> key:" + key.toString());
        return redisTemplate.opsForHash().delete(id, key);
    }

    @Override
    public void clear() {
        RedisTemplate<Object,Object> redisTemplate =
                (RedisTemplate<Object,Object>) ApplicationContextUtils.getBean("redisTemplate");
        log.info("RedisCache clear");
        redisTemplate.opsForHash().delete(id);
    }

    @Override
    public int getSize() {
        RedisTemplate<Object,Object> redisTemplate =
                (RedisTemplate<Object,Object>) ApplicationContextUtils.getBean("redisTemplate");
        log.info("RedisCache getSize");
        return redisTemplate.opsForHash().size(id).intValue();
    }

}